<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import api from '../../util/api'
import { saveJwt, parseJwt } from '@/api/jwt'
import router from "@/router/index.js";
// 表单数据
const form = reactive({
  email: '',
  code: '',
  password: '',
  confirmPassword: ''
})

// 错误信息
const errors = reactive({
  email: '',
  code: '',
  password: '',
  confirmPassword: ''
})

// 状态变量
const isSending = ref(false)
const countdown = ref(0)
const isRegistering = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

// 验证邮箱格式
const isEmailValid = computed(() => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(form.email)
})

// 发送验证码
const sendVerificationCode = async () => {
  // 重置错误信息
  errors.email = ''
  errorMessage.value = ''

  // 验证邮箱
  if (!form.email) {
    errors.email = '请输入邮箱地址'
    return
  }

  if (!isEmailValid.value) {
    errors.email = '请输入有效的邮箱地址'
    return
  }

  isSending.value = true

  try {
    // 调用发送验证码API
    await api({
        url: '/auth/send-code',
        method: 'get',
        params: {
          email: form.email
        }
    })

    successMessage.value = '验证码已发送到您的邮箱'
    countdown.value = 300

    // 开始倒计时
    const timer = setInterval(() => {
      if (countdown.value <= 0) {
        clearInterval(timer)
      } else {
        countdown.value--
      }
    }, 1000)
  } catch (error: any) {
    errorMessage.value = '发送验证码失败: ' + (error.response?.data?.message || '请稍后重试')
  } finally {
    isSending.value = false
  }
}

// 注册用户
const register = async () => {
  // 重置错误信息
  errors.email = ''
  errors.code = ''
  errors.password = ''
  errors.confirmPassword = ''
  errorMessage.value = ''
  successMessage.value = ''

  // 表单验证
  let isValid = true

  if (!form.email) {
    errors.email = '请输入邮箱地址'
    isValid = false
  } else if (!isEmailValid.value) {
    errors.email = '请输入有效的邮箱地址'
    isValid = false
  }

  if (!form.code) {
    errors.code = '请输入验证码'
    isValid = false
  } else if (form.code.length !== 6) {
    errors.code = '验证码为6位数字'
    isValid = false
  }

  if (!form.password) {
    errors.password = '请输入密码'
    isValid = false
  } else if (form.password.length < 6) {
    errors.password = '密码长度至少为6位'
    isValid = false
  }

  if (form.password !== form.confirmPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }

  if (!isValid) return

  isRegistering.value = true

  try {
    // 调用注册API
    const response = await api.post('/auth/register', {
      email: form.email,
      code: form.code,
      password: form.password
    })

    // 保存JWT
    if (response.data) {
      saveJwt(response.data)

      // 解析JWT（可选）
      const payload = parseJwt(response.data)
      console.log("Authorization:", payload)
    }

    successMessage.value = '注册成功！正在跳转...'
    // 模拟跳转
    setTimeout(() => {
      // 实际项目中跳转到首页
      router.push('/login')
      alert('注册成功，跳转到登录')
    }, 1500)
  } catch (error: any) {
    errorMessage.value = '注册失败: ' + (error.response?.data?.message || '请稍后重试')
  } finally {
    isRegistering.value = false
  }
}
</script>

<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <h1>创建账户</h1>
        <p>开启您的个性化体验之旅</p>
      </div>

      <div class="register-form">
        <div class="form-group">
          <label for="email">电子邮箱</label>
          <div class="input-group">
            <input
                type="email"
                id="email"
                v-model="form.email"
                placeholder="请输入您的邮箱"
                :class="{'error': errors.email}"
            >
            <button
                class="btn-outline"
                @click="sendVerificationCode"
                :disabled="isSending || !isEmailValid || countdown > 0"
            >
              <span v-if="isSending" class="btn-loading">
                <span class="loading-spinner"></span>发送中
              </span>
              <span v-else-if="countdown > 0">
                {{ countdown }}秒后重试
              </span>
              <span v-else>
                获取验证码
              </span>
            </button>
          </div>
          <div class="error-message">{{ errors.email }}</div>
        </div>

        <div class="form-group">
          <label for="code">验证码</label>
          <input
              type="text"
              id="code"
              v-model="form.code"
              placeholder="请输入验证码"
              :class="{'error': errors.code}"
          >
          <div class="error-message">{{ errors.code }}</div>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
              type="password"
              id="password"
              v-model="form.password"
              placeholder="设置您的密码"
              :class="{'error': errors.password}"
          >
          <div class="error-message">{{ errors.password }}</div>
        </div>

        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <input
              type="password"
              id="confirmPassword"
              v-model="form.confirmPassword"
              placeholder="请再次输入密码"
              :class="{'error': errors.confirmPassword}"
          >
          <div class="error-message">{{ errors.confirmPassword }}</div>
        </div>

        <div class="form-group">
          <button class="btn-primary" @click="register" :disabled="isRegistering">
            <span v-if="isRegistering" class="btn-loading">
              <span class="loading-spinner"></span> 注册中...
            </span>
            <span v-else>
              立即注册
            </span>
          </button>
          <div class="success-message">{{ successMessage }}</div>
          <div class="error-message">{{ errorMessage }}</div>
        </div>
      </div>

      <div class="register-footer">
        <p>已有账号？<router-link to="/login">立即登录</router-link></p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 500px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.register-header {
  background: linear-gradient(to right, #4776E6, #8E54E9);
  color: white;
  padding: 25px 30px;
  text-align: center;
}

.register-header h1 {
  font-weight: 500;
  font-size: 28px;
  margin-bottom: 5px;
}

.register-header p {
  opacity: 0.9;
  font-size: 16px;
}

.register-form {
  padding: 30px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.input-group {
  display: flex;
  gap: 10px;
}

.input-group input {
  flex: 1;
}

input {
  width: 100%;
  padding: 14px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  border-color: #4776E6;
  outline: none;
  box-shadow: 0 0 0 2px rgba(71, 118, 230, 0.2);
}

input.error {
  border-color: #e74c3c;
}

.btn-primary {
  padding: 14px 20px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  background: linear-gradient(to right, #4776E6, #8E54E9);
  color: white;
  width: 100%;
}

.btn-primary:hover {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.btn-primary:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-outline {
  padding: 14px 20px;
  background: transparent;
  border: 1px solid #4776E6;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  color: #4776E6;
  min-width: 120px;
}

.btn-outline:hover {
  background-color: rgba(71, 118, 230, 0.1);
}

.btn-outline:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background-color: #f5f5f5;
}

.error-message {
  color: #e74c3c;
  font-size: 14px;
  margin-top: 5px;
  height: 20px;
}

.success-message {
  color: #2ecc71;
  font-size: 14px;
  margin-top: 5px;
  height: 20px;
  text-align: center;
}

.register-footer {
  text-align: center;
  padding: 20px;
  border-top: 1px solid #eee;
  font-size: 14px;
  color: #666;
}

.register-footer a {
  color: #4776E6;
  text-decoration: none;
  font-weight: 500;
}

.btn-loading {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255,255,255,.3);
  border-radius: 50%;
  border-top-color: currentColor;
  animation: spin 1s ease-in-out infinite;
  margin-right: 8px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@media (max-width: 600px) {
  .register-card {
    margin: 10px;
  }

  .register-form {
    padding: 20px;
  }

  .input-group {
    flex-direction: column;
  }
}
</style>